package 并发编程.自定义FutureTask;

import java.util.concurrent.*;

/**
 *
 * */
public class MyFutureTask<V> implements RunnableFuture<V> {
    private Callable callable;
    private V result = null;

    private String name;

    public MyFutureTask(Callable callable, String name) {
        this.callable = callable;
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " run 开始 " + name);
        try {
            result = (V) callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
        synchronized (this) {
            this.notifyAll();
        }
        System.out.println(Thread.currentThread() + " run 结束 " + name);
    }

    @Override
    public V get() throws InterruptedException, ExecutionException {
        System.out.println(Thread.currentThread() + " get 开始 " + name);
        if (result != null) {
            System.out.println(" result is not  null");
            return result;
        }


        /*try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        synchronized (this) {
            this.wait();
        }
        System.out.println(Thread.currentThread() + " get 结束 " + name);
        return result;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return false;
    }


    @Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return null;
    }
}
